package com.tron.dobest.nettysocket;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.ContinuationWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;

@Sharable
public class TronBinaryWebSocketFrameHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private ByteBuf buf = Unpooled.buffer();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame webSocketFrame) throws Exception {
        if (webSocketFrame instanceof BinaryWebSocketFrame) {
            System.out.println("一次搞定");
            System.out.println(webSocketFrame.content().readableBytes());
            if (!webSocketFrame.isFinalFragment() && buf != null) {
                buf.writeBytes(webSocketFrame.content());
            } else {
                ChannelFuture future = ctx.writeAndFlush(new BinaryWebSocketFrame(webSocketFrame.content()));
                if (future.isSuccess()) {
                    buf = null;
                }
            }
        }
        if (webSocketFrame instanceof ContinuationWebSocketFrame) {
            System.out.println("多次搞定");
            System.out.println(webSocketFrame.content().readableBytes());
            if (!webSocketFrame.isFinalFragment()) {
                buf.writeBytes(webSocketFrame.content());
            } else {
                ChannelFuture future = ctx.writeAndFlush(new BinaryWebSocketFrame(buf));
                if (future.isSuccess()) {
                    buf = null;
                }
            }
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }

}
